<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8"
          ><!-- 搜索与添加 -->
          <el-input
            clearable
            placeholder="请输入用户名或手机号（模糊搜索）"
            v-model="queryInfo.query"
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button> </el-input
        ></el-col>
        <el-col :span="4"
          ><el-button type="primary" @click="addDialogVisible = true"
            >添加用户</el-button
          ></el-col
        >
      </el-row>
      <el-row>
        <!-- 用户列表区域 -->
        <el-table :data="userList" border stripe>
          <el-table-column type="index"> </el-table-column>
          <el-table-column prop="user.username" label="用户名">
          </el-table-column>
          <el-table-column prop="user.phone_number" label="电话">
          </el-table-column>
          <!-- <el-table-column prop="address" label="地址"> </el-table-column> -->
          <el-table-column label="状态">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.delete_time != null" type="danger"
                >被删除</el-tag
              >
              <el-tag v-else type="info">正常</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <!-- 详细信息 -->
              <el-tooltip
                :enterable="false"
                effect="dark"
                content="详细信息"
                placement="top"
              >
                <el-button
                  type="primary"
                  icon="el-icon-postcard"
                  circle
                  @click="showInfoDialog(scope.row.user.id)"
                ></el-button>
              </el-tooltip>

              <!-- 修改按钮 -->
              <el-tooltip
                :enterable="false"
                effect="dark"
                content="修改"
                placement="top"
              >
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  circle
                  @click="showEditDialog(scope.row.user.id)"
                ></el-button>
              </el-tooltip>

              <!-- 删除按钮 -->
              <el-tooltip
                :enterable="false"
                effect="dark"
                content="删除"
                placement="top"
              >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  circle
                  @click="removeUserById(scope.row)"
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页区域 -->
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pageNum"
          :page-sizes="[5, 10, 20]"
          :page-size="queryInfo.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </el-row>
    </el-card>

    <!-- 添加用户的对话框 -->
    <el-dialog
      @close="addDialogClosed"
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="60%"
    >
      <!-- 内容主体区 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone_number">
          <el-input v-model="addForm.phone_number"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部按钮区 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 查看详细信息 -->
    <!-- 修改用户的对话框 -->
    <el-dialog
      @close="editDialogClosed"
      title="修改用户"
      :visible.sync="editDialogVisible"
      width="60%"
    >
      <!-- 内容主体区 -->
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="70px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="id">
              <el-input v-model="editForm.id" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input
                v-model="editForm.username"
                :disabled="is_info || editForm.delete_time != null"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="手机号" prop="phone_number">
          <el-input v-model="editForm.phone_number" disabled></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="editForm.password"
            @input="handleInput()"
            :disabled="is_info || editForm.delete_time != null"
          ></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>

        <el-form-item label="是否删除" prop="delete_time">
          <el-tag v-if="editForm.delete_time != null" type="danger"
            >被删除</el-tag
          >
          <el-tag v-else type="info">正常</el-tag>
        </el-form-item>
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="创建时间" prop="create_time">
              <el-input
                :value="editForm.create_time | dateFormat"
                disabled
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="更新时间" prop="update_time">
              <el-input
                :value="editForm.update_time | dateFormat"
                disabled
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="editForm.delete_time != null">
            <el-form-item label="删除时间" prop="delete_time">
              <el-input
                :value="editForm.delete_time | dateFormat"
                disabled
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 底部按钮区 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser" v-show="!is_info"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 验证手机号规则
    const checkMobile = (rule, value, cb) => {
      // 验证手机号的正则表达式
      const regMobile =
        /^(0|86|17951)?(13[0-9]|15[0-9]|17[678]|18[0-9]|14[57])[0-9]{8}$/

      if (regMobile.test(value)) {
        // 合法的邮箱
        return cb()
      }

      cb(new Error('请输入合法的手机号'))
    }

    return {
      // 获取用户列表的参数对象
      queryInfo: {
        query: '',
        // 当前页面数
        pageNum: 1,
        // 当前每页显示多少条数据
        pageSize: 5
      },
      // 用户列表
      userList: [],
      // 总数据条数
      total: 0,
      is_info: false,
      // 控制对话框的显示与隐藏
      addDialogVisible: false,
      // 添加用户的表单数据
      addForm: {
        username: '',
        password: '',
        email: '',
        phone_number: ''
      },
      // 添加用户表单的验证规则对象
      addFormRules: {
        username: [
          {
            required: true,
            message: '请输入用户名',
            trigger: 'blur'
          },
          {
            min: 3,
            max: 12,
            message: '用户名长度在3 ~ 12之间',
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          },
          { min: 8, max: 15, message: '长度在 8 到 15 个字符', trigger: 'blur' }
        ],

        phone_number: [
          {
            required: true,
            message: '请输入电话',
            trigger: 'blur'
          },
          {
            validator: checkMobile,
            trigger: 'blur'
          }
        ]
      },
      // 控制修改用户对话框的显示与隐藏
      editDialogVisible: false,
      // 修改表单的数据
      editForm: {
        id: 0,
        username: '',
        phone_number: '',
        email: '',
        delete_time: null,
        password: '878923',
        create_time: null,
        update_time: null
      },
      // 修改表单的验证规则对象
      editFormRules: {
        password: [
          {
            required: false,
            message: '请输入密码',
            trigger: 'blur'
          },
          { min: 8, max: 15, message: '长度在 8 到 15 个字符', trigger: 'blur' }
        ]
      },
      // 需要被分配角色的用户信息
      userInfo: {}
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get('/getUserInfoList', {
        params: this.queryInfo
      })
      // console.log(res)
      if (res.status !== 200) {
        return this.$message.error('获取用户列表失败')
      }

      this.userList = res.data.data
      this.total = res.data.totalNum
    },
    // 监听 pagesize 改变的事件
    handleSizeChange(newSize) {
      this.queryInfo.pageSize = newSize
      this.getUserList()
    },
    // 监听 页码值 改变的事件
    handleCurrentChange(newPage) {
      this.queryInfo.pageNum = newPage
      this.getUserList()
    },

    // 监听添加用户对话框是否关闭
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    // 点击按钮，添加新用户
    addUser() {
      // 表单结果验证
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return
        // 可以发起添加新用户的请求
        const { data: res } = await this.$http.post('/addUser', this.addForm)
        // console.log('ress', res)
        if (res.status !== 200) {
          // console.log(res)
          return this.$message.error(res.message)
        }
        this.$message.success('添加用户成功')
        // 隐藏添加用户的对话框
        this.addDialogVisible = false
        // 重新获取用户列表数据以更新
        this.getUserList()
      })
    },

    showInfoDialog(id) {
      this.is_info = true
      this.showEditDialog(id)
    },
    // 展示编辑用户的对话框
    async showEditDialog(id) {
      const { data: res } = await this.$http.get(`/getUserInfoById?id=${id}`)
      if (res.status !== 200) {
        return this.$message.error('查询用户信息失败')
      }

      // console.log(res.data)
      this.editForm = {
        create_time: res.data.create_time,
        delete_time: res.data.delete_time,
        update_time: res.data.update_time,
        ...res.data.user,
        password: '' // 保留原始密码或设为空
      }
      this.editForm.password = ''
      this.editDialogVisible = true
    },
    // 监听修改用户对话框关闭事件
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
      this.editDialogVisible = false
      this.is_info = false
    },
    handleInput(e) {
      console.log(e)
    },

    // },
    editUser() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return
        // 发起修改用户信息的请求
        const { data: res } = await this.$http.post(
          '/updateUser',
          this.editForm
        )
        if (res.status !== 200) {
          return this.$message.error(res.msg)
        }
        // 关闭对话框
        this.editDialogVisible = false
        // 更新数据
        this.getUserList()
        // 提示修改成功
        this.$message.success('修改用户信息成功')
      })
    },
    // 根据id删除用户信息
    async removeUserById(user) {
      const isDeleted = user.delete_time == null
      const text = isDeleted ? '删除' : '恢复'

      // 弹框询问删除
      const confirmRes = await this.$confirm(
        '是否' + text + '该用户信息',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)

      // 如果用户确认删除，返回的是文本confirm
      // 如果用户取消删除，返回的是cancel
      if (confirmRes !== 'confirm') {
        return this.$message.info('已取消删除')
      }

      // this.editUserDeleted(id, true)
      const { data: res } = await this.$http.post('/deleteUser', {
        userId: user.user.id,
        flag: isDeleted
      })
      if (res.status !== 200) {
        return this.$message.error(text + '用户信息失败')
      }
      // 更新数据
      this.getUserList()
      this.$message.success(text + '用户信息成功')
    }
  }
}
</script>

<style lang="less" scoped></style>
